package handler

import (
	"fmt"
	"iot-base/common/eventtype"
	rc "iot-base/common/redis"
	"iot-base/common/timer"
	"time"

	"github.com/vmihailenco/msgpack/v5"
)

const CLEAR_CACHE = "cache_clear_alarm"

func makeDelayKey(tid, alarmID string, index int64) string {
	return fmt.Sprintf("%s.%s.%s.%d.", CLEAR_CACHE, tid, alarmID, index)
}

var alarmChanFromEvent chan *eventtype.Alarm

func handleDelay(curAlarm *eventtype.Alarm, delay int64, alarmChan chan *eventtype.Alarm) {
	//delay := curAlarm.Delay

	alarmChanFromEvent = alarmChan
	key := makeDelayKey(curAlarm.TID, curAlarm.AlarmID, curAlarm.Mindex)

	freachTime := float64(delay + curAlarm.ClearTime)
	fdate, err := rc.ZScore(CLEAR_CACHE, key)
	if (err == nil && fdate < freachTime) || err != nil {
		rc.AddScore(CLEAR_CACHE, key, float64(delay+curAlarm.ClearTime))
		bmsg, _ := msgpack.Marshal(curAlarm)
		rc.Set(key, bmsg, 0)
	}

}

const checkPriod = 5

func init() {
	timer.BeginTimerThrd(checkPriod, false, false, func() {
		//key := makeDelayKey(curAlarm.TID, curAlarm.AlarmID, curAlarm.Mindex)
		cids, err := rc.ZRangeByScore(CLEAR_CACHE, 0, float64(time.Now().Unix()))
		if err == nil && cids != nil {
			for _, clear := range cids {
				sclear, _ := rc.Get(clear).Result()
				if len(sclear) > 0 {
					var curAlarm eventtype.Alarm
					err = msgpack.Unmarshal([]byte(sclear), &curAlarm)
					if err == nil {
						HandleClear(&curAlarm, alarmChanFromEvent)
					}
				}
				rc.Del(clear)
				rc.RemoveKeyFromSet(CLEAR_CACHE, clear)
			}
		}
	})
}
